import os
from itertools import zip_longest

code = "utf_8_sig"    # utf8-bom, paradox coding
modpath = r'D:\\Documents\\Paradox Interactive\\Crusader Kings III\\mod\\character\\'
# 次级图包路径，置空则不分子文件夹
dir = "BangDream"
# alterdir = "ARKmisc"
trait_prefix = "BangDream_"
modprefix = "MyGO_"
template_path = "common\\scripted_character_templates"
#是否拥有少女乐队成员特质
has_girlsband_member_trait = True
# inputs: xls直接转为csv即可
inputs = open("./BDP.csv", "r", encoding=code)
templates = open(os.path.join(modpath, template_path, trait_prefix+"templates.txt"), "w+", encoding=code)
templates2 = open(os.path.join(modpath, template_path, trait_prefix+"misc_templates.txt"), "w+", encoding=code)
effects = open(os.path.join(modpath, "common\\scripted_effects\\BangDream_character_effects.txt"), "w+", encoding=code)
# mod的图包路径
# assetpath = "resource\\hm_prophet"
assetpath = "gfx\\models\\portraits\\props"
workplace = os.path.join(modpath, assetpath, dir)
# workplace2 = os.path.join(modpath, assetpath, alterdir)
traitdict = open("./traits.txt", "r", encoding=code)
# racedict = open("./racedict.txt", "r", encoding=code)
localizations = "localization\\simp_chinese"
special = os.path.join(modpath, template_path, "special_"+trait_prefix+"templates.txt")
locked = list()
if os.path.exists(special):
    special_temp = open(special, "r", encoding=code)
    for line in special_temp:
        if "_template" in line:
            locked.append(line.replace("_template = {"))
alterloc = open(os.path.join(modpath, localizations, trait_prefix+"characters_trait_l_simp_chinese.yml"), "w+", encoding=code)
alterloc.write("l_simp_chinese:\n")

nameloc = open(os.path.join(modpath, localizations, trait_prefix+"characters_name_l_simp_chinese.yml"), "w+", encoding=code)
nameloc.write("l_simp_chinese:\n")
dynnloc = open(os.path.join(modpath, localizations, trait_prefix+"dynn_name_l_simp_chinese.yml"), "w+", encoding=code)
dynnloc.write("l_simp_chinese:\n")


def replace(x, old, new=None, strip=False) -> str:
    '''批量替换字符串内容

    :param x: 原始字符串
    :param old: 要替换的内容，可为 `str` , `list`
    :param new: 新内容，可为 `str` , `list` , `None`
    :param strip: 是否删除前后空格

    >>> replace('10000阅读', old='阅读')
    '10000'
    >>> replace('文章10000阅读', old=['文章', '阅读'])
    '10000'
    >>> replace('10000阅读', old='阅读', new='点击')
    '10000点击'
    >>> replace('文章10000阅读', old=['文章', '阅读'], new=[None, '点击'])
    '10000点击'
    >>> replace('文章10000阅读', old=['文章', '阅读'], new=['', '点击'])
    '10000点击'
    >>> replace('文章10000阅读', old=['文章', '阅读'], new=['美文'])
    '美文10000'
    '''
    if not new:
        new = ''
    if isinstance(old, str):
        x = x.replace(old, new)
    if isinstance(old, list):
        for _old, _new in zip_longest(old, new, fillvalue=''):
            if _new is None:
                _new = ''
            x = x.replace(_old, _new)
    if strip:
        x = x.strip()
    return x


# trait name dicts
new = list()
old = list()
for line in traitdict:
    old.append(line.strip("\n").split("\t")[1])
    new.append(line.strip("\n").split("\t")[0])
ddslist = os.listdir(workplace)
# ddslist2 = os.listdir(workplace2)
waifu = list()
for file in ddslist:
    if os.path.isfile(os.path.join(workplace, file)):
        if file[-14:] == '_0_diffuse.dds':
            waifu.append(file[:-14])
# for file in ddslist2:
#     if os.path.isfile(os.path.join(workplace2, file)):
#         if file[-14:] == '_0_diffuse.dds':
#             waifu.append(file[:-14])
waifu_backup = waifu.copy()
count = 0
nonOperator = False
NPCs = []
for line in inputs:
    if count <= 2:
        count += 1
        continue
    name = line.split(",")[1]
    if name == "":
        nonOperator = True
        continue
    # name = trait_prefix + name
    nameloc.write(' '+name+': "'+line.split(",")[3]+'"\n')
    if nonOperator:
        NPCs.append(name)
        if line.split(",")[-1].strip() == "":
            alterloc.write(' trait_'+name+'_desc: "这是一位暂时缺少介绍文本/角色模板/特质加成的角色，欢迎加群321965685来帮忙出主意"\n')
        else:
            alterloc.write(' trait_'+name+': "'+line.split(",")[-1].replace('"','').replace('\n','')+'"\n')
        writeto = templates2
    else:
        alterloc.write(' trait_'+name+': "'+line.split(",")[2]+'"\n')
        if line.split(",")[-1].strip() == "":
            alterloc.write(' trait_'+name+'_desc: "这是一位暂时缺少介绍文本/角色模板/特质加成的角色，欢迎加群321965685来帮忙出主意"\n')
        else:
            alterloc.write(' trait_'+name+'_desc: "'+line.split(",")[-1].replace('"','').replace('\n','')+'"\n')
        writeto = templates
    if name in waifu and name not in locked:
        waifu.remove(name)
        writeto.write(name+'''_template = {
\tname = "'''+name+'''"
\ttrait = '''+name+'''
''')
        if has_girlsband_member_trait == True:
            writeto.write('''\ttrait = girlsband_member ''')
        writeto.write('''
\tage = 16
\tgender = '''+("male" if line.split(",")[4] == "男" else "female")+'''
\tintrigue = { 12 15 }
\tmartial = { 12 15 }
\tdiplomacy = { 12 15 }
\tstewardship = { 12 15 }
\tlearning = { 12 15 }
\tprowess = { 12 15 }
''')
        traits = replace(line.strip("\n"), old, new).split(",")[5:-2]
        while "" in traits:
            traits.remove("")
        if len(traits) >= 1:
            # print(replace(line.strip('\n'), old, new))
            if len(traits) < 4:
                print(name, "has less than 4 traits!")
            for trait in traits:
                writeto.write("\ttrait = "+trait+"\n")
            writeto.write("\trandom_traits = no\n")
        else:
            writeto.write("\trandom_traits = yes\n")
        writeto.write("\tafter_creation = {\n")
        writeto.write("\t\tset_ethnicity = anime_ethnicity\n")
        writeto.write("\t\tset_sexuality = homosexual")
        # sexuality = line.split(",")[5]
        # if sexuality == "异性恋":
        #     writeto.write("\t\tset_sexuality = heterosexual")
        # elif sexuality == "同性恋":
        #     writeto.write("\t\tset_sexuality = homosexual")
        # elif sexuality == "双性恋":
        #     writeto.write("\t\tset_sexuality = bisexual")
        # elif sexuality == "无性恋":
        #     writeto.write("\t\tset_sexuality = asexual")
        # else:
        #     writeto.write("\t\tgame_rule_sexuality_distribution_reroll_effect = yes")
         # dynasty name force set
            # use special family name if exists
        familynameindex = name
        writeto.write("\n\t\tdynasty = { set_dynasty_name = dynn_" + familynameindex + " }")
        writeto.write("\n\t\thouse = { set_house_name_from_dynasty = prev.dynasty }")
        writeto.write("\n\t}\n}\n")
        dynnloc.write(' dynn_' + familynameindex + ': "'+line.split(",")[4].replace('"','').replace('\n','')+'"\n')

for name in waifu:
    if name not in locked:
        if name in NPCs:
            writeto = templates2
        else:
            writeto = templates
        writeto.write(name+'''_template = {
\tname = "trait_'''+name+'''"
\ttrait = '''+name+'''

\tage = 16
\tgender = female
\tintrigue = { 12 15 }
\tmartial = { 12 15 }
\tdiplomacy = { 12 15 }
\tstewardship = { 12 15 }
\tlearning = { 12 15 }
\tprowess = { 15 20 }
\trandom_traits = yes
\tafter_creation = {
\t\tgame_rule_sexuality_distribution_reroll_effect = yes
\t}
}
''')

effects.write('''create_BangDream_character_effect = {
\tsave_scope_as = employer
\thidden_effect_new_object = {
\t\trandom_list = {''')
for name in waifu_backup:
    if name not in NPCs:
        effects.write('''
\t\t\t1 = {
\t\t\t\ttrigger = {
\t\t\t\t\tNOT = {
\t\t\t\t\t\tis_target_in_global_variable_list = {
\t\t\t\t\t\t\tname = MyGO_character_exist
\t\t\t\t\t\t\ttarget = trait:'''+name+'''
\t\t\t\t\t\t}
\t\t\t\t\t}
\t\t\t\t}
\t\t\t\tcreate_character = {
\t\t\t\t\ttemplate = '''+name+'''_template
\t\t\t\t\temployer = scope:employer
\t\t\t\t\tsave_scope_as = invited_character
\t\t\t\t}
\t\t\t}''')
effects.write('''
\t\t}
\t\thidden_effect = {
\t\t\tsend_interface_toast = {
\t\t\t\ttitle = MyGO_add_character_events.0001.toast
\t\t\t\tleft_icon = scope:invited_character
\t\t\t\tadd_courtier = scope:invited_character
\t\t\t}
\t\t}
\t\tscope:invited_character = {
\t\t\ton_girlsband_character_created_effect = yes
\t\t}
\t}
}
''')
count = 1
effects.write('''set_girlsband_name_effect = {\n''')
for name in waifu_backup:
    if name not in NPCs:
        if count == 1:
            effects.write('''\tif = { limit = { has_trait = '''+name+''' } change_first_name = "'''+name+'''" }\n''')
            count = count + 1
        else:
            effects.write('''\telse_if = { limit = { has_trait = '''+name+''' } change_first_name = "'''+name+'''" }\n''')
prevband = "defualt"
count = 1
for name in waifu_backup:
    band = name.split("_")[0]
    if count == 1:
        count = count +1
        effects.write('''
}''')
        effects.write('''\nadd_randomised_'''+band+'''_trait = {
\thidden_effect = {
\t\trandom_list = {
\t\t\t1 = { add_trait = '''+name+''' }\n''')
        prevband = band
    if prevband != band:
        effects.write('''\t\t}
\t\tset_ethnicity = anime_ethnicity
\t}
}''')
        effects.write('''\nadd_randomised_'''+band+'''_trait = {
\thidden_effect = {
\t\trandom_list = {
\t\t\t1 = { add_trait = '''+name+''' }\n''')
        prevband = band
    else:
        effects.write('''\t\t\t1 = { add_trait = '''+name+''' }\n''')
effects.write('''\t\t}
\t\tset_ethnicity = anime_ethnicity
\t}
}''')
templates.close()
effects.close()
alterloc.close()
templates2.close()
